<?php
/**
 * File: App\Controller\PostController.php
 */

declare(strict_types=1);

namespace App\Controller;

use App\Service\PostService;
use Spiral\Prototype\Traits\PrototypeTrait;

class PostController
{
    use PrototypeTrait;

    private $service;

    public function __construct(PostService $service)
    {
        $this->service = $service;
    }

    public function getPost(int $id = null)
    {
        if (is_int($id)) { // 传入 $id 的是查看文章详情
            $post = $this->service->getPost($id);
            if (!$post) {
                // 文章不存在，返回 404
                return $this->response->html('Page not found', 404);
            } else {
                return $this->views->render('posts/single', [ 'post' => $post]);
            }
        } else { // 否则是查看文章列表
            $page = (int) $this->input->query('page', 1);
            $size = (int) $this->input->query('size', 5);
            $page = $page > 0 ? $page :  1;
            $size = $size > 0 ? $size : 10;

            // $data 包含 'posts' 和 'pages' 两个 key
            $data = $this->service->getPosts($page, $size);
            return $this->views->render('posts/list', [
                'posts' => $data['posts'],
                'pages' => $data['pages'],
                'page' => $page,
                'size' => $size
            ]);
        }
    }

    public function postPost($id = null): string
    {
        return "创建文章";
    }

    public function putPost(int $id = null): string
    {
        return "编辑文章";
    }

    public function deletePost(int $id = null): string
    {
        return is_int($id) ? "删除文章 $id" : "参数缺失";
    }
}
